﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AMStudio.Common;
using Microsoft.Practices.ServiceLocation;
using AMStudio.DelegateDispather;
using AMStudio.Windows.Forms;
using System.Diagnostics;
using AMStudio.Log;
//using Microsoft.Practices.Unity;
//using Microsoft.Practices.Unity.Configuration;

namespace AMStudio.UserInterface
{
    public partial class BaseUI : AWinFormShell
    {
        private bool loginSuccess = false;
        //private MaterialForm materialForm;
        public BaseUI()
        {
            //LoginForm login = new LoginForm();

            //if (login.ShowDialog() == DialogResult.OK)
            //{
            //    loginSuccess = true;

            //}
            //else
            //{
            //    this.Visible = false;
            //    Application.Exit();
            //}
            InitializeComponent();
            //this.Tag = this.GetHashCode();


        }

        private void BaseUI_Load(object sender, EventArgs e)
        {
            //if (!loginSuccess)
            //{
            //    Application.Exit();
            //    return;
            //}

            this.Initialize();
            //container = new UnityContainer();
            //container.LoadConfiguration();
            this.ActiveModule("MainUI");
            base.SubscribeEvent("MANAGER_RET");
            this.ErrorList.TreeItemChecked += new EventHandler<ItemCheckedEventArgs>(ErrorList_TreeItemChecked);
            AEventManager myManager = ServiceLocator.Current.GetInstance<IEventManager>("EventManager") as AEventManager;
            //int a = myManager.GetHashCode();
            myManager.RunAsync();
            EventBroker.RegisterPublisher("SET_USER_PRIVILIGE", this, "SetUserPriviligeEvent");
            //EventBroker.RegisterPublisher("SET_LANGUAGE", this, "SetLanguageEvent");   
            SetUserPrivilige();
            //materialForm = new MaterialForm();
            //this.materialForm.EventClient = this.EventClient;

            
        }

        void ErrorList_TreeItemChecked(object sender, ItemCheckedEventArgs e)
        {
            string code = e.Item.SubItems[0].Text.ToString().Trim();
            //int st_index = int.Parse(code.Substring(0, 2));
            SendMessage("ACTIVE_ERROR", code);

        }

        protected override void Language_RfreshTag(LanguageItem item)
        {
            base.Language_RfreshTag(item);

            if (item.RelatedControl is BaseUI)
            {

                if ((item != null) && (item.Language[LanguageString] != null))
                {
                    string[] titles = item.Language[LanguageString].ToString().Split(new string[] { "||" }, StringSplitOptions.None);

                    if (titles.Length > 0)
                    {
                        this.ribbonOperation.Text = titles[0];
                        if (titles.Length > 1)
                        {
                            this.ribbonProduction.Text = titles[1];
                            if (titles.Length > 2)
                            {
                                this.ribbonStatistics.Text = titles[2];
                                if (titles.Length > 3)
                                {
                                    this.ribbonManagement.Text = titles[3];
                                    if (titles.Length > 4)
                                    {

                                        this.buttonItemLogin.Text = titles[4];

                                        if (titles.Length > 5)
                                        {
                                            this.buttonItemClose.Text = titles[5];
                                        }
                                    }
                                }
                            }
                        }
                    }

                    this.ribbonControl1.Refresh();

                }


            }

            if (item.RelatedControl is DevComponents.DotNetBar.RibbonBar)
            {
                DevComponents.DotNetBar.RibbonBar bar = item.RelatedControl as DevComponents.DotNetBar.RibbonBar;
                if (bar.Items.Count > 0)
                {
                    if ((item != null) && (item.Language[LanguageString] != null))
                    {
                        string[] titles = item.Language[LanguageString].ToString().Split(new string[] { "||" }, StringSplitOptions.None);
                        if (titles.Length >= bar.Items.Count + 1)
                        {
                            bar.Text = titles[0];

                            for (int i = 0; i < bar.Items.Count; i++)
                            {
                                bar.Items[i].Text = titles[i + 1];
                            }
                        }
                    }
                    item.RelatedControl.Refresh();
                }
            }

            if (item.RelatedControl.Name.ToString().ToUpper()=="ERRORLIST")
            {
                string[] titles = item.Language[LanguageString].ToString().Split(new string[] { "||" }, StringSplitOptions.None);

                if (titles.Length >= 3)
                {
                    for (int i = 0; i < titles.Length; i++)
                    {
                        this.ErrorList.Columns[i].Text = titles[i];
                    }
                }
            }

            if (item.RelatedControl.Name.ToString().ToUpper() == "CONDITIONLIST")
            {
                string[] titles = item.Language[LanguageString].ToString().Split(new string[] { "||" }, StringSplitOptions.None);

                if (titles.Length >= 3)
                {
                    for (int i = 0; i < titles.Length; i++)
                    {
                        this.ConditionList.Columns[i].Text = titles[i];
                    }
                }
            }
        }


        protected override void Language_InitializeControl(Control UIControl)
        {
            base.Language_InitializeControl(UIControl);
            if (UIControl is BaseUI)
            {
                LanguageItem item = LanguageDB.UIDBTags[this.UIName + "."] as LanguageItem;
                if ((item!=null) && (item.Language[LanguageString]!=null))
                {
                    string[] titles = item.Language[LanguageString].ToString().Split(new string[] { "||" }, StringSplitOptions.None);

                    if (titles.Length > 0)
                    {
                        this.ribbonOperation.Text = titles[0];
                        if (titles.Length > 1)
                        {
                            this.ribbonProduction.Text = titles[1];
                            if (titles.Length > 2)
                            {
                                this.ribbonStatistics.Text = titles[2];
                                if (titles.Length > 3)
                                {
                                    this.ribbonManagement.Text = titles[3];

                                    if (titles.Length > 4)
                                    {

                                        this.buttonItemLogin.Text = titles[4];

                                        if (titles.Length>5)
                                        {
                                            this.buttonItemClose.Text = titles[5];
                                        }
                                    }
                                }
                            }
                        }
                    }

                    this.ribbonControl1.Refresh();
                   
                }
                
                
            }

            if (UIControl is DevComponents.DotNetBar.RibbonBar)
            {
                DevComponents.DotNetBar.RibbonBar bar = UIControl as DevComponents.DotNetBar.RibbonBar;
                if (bar.Items.Count > 0)
                {
                    LanguageItem item = LanguageDB.UIDBTags[this.UIName + "." + bar.Name] as LanguageItem;
                    if ((item != null) && (item.Language[LanguageString] != null))
                    {
                        string[] titles = item.Language[LanguageString].ToString().Split(new string[] { "||" }, StringSplitOptions.None);
                        if (titles.Length >= bar.Items.Count + 1)
                        {
                            bar.Text = titles[0];

                            for (int i = 0; i < bar.Items.Count; i++)
                            {
                                bar.Items[i].Text = titles[i + 1];
                            }
                        }
                    }
                    bar.Refresh();
                }
            }



            if (UIControl.Name.ToString().ToUpper() == "ERRORLIST")
            {
                ListView bar = UIControl as ListView;


                LanguageItem item = LanguageDB.UIDBTags[this.UIName + "." + bar.Name] as LanguageItem;
                if ((item != null) && (item.Language[LanguageString] != null))
                {
                    string[] titles = item.Language[LanguageString].ToString().Split(new string[] { "||" }, StringSplitOptions.None);

                    if (titles.Length >= 3)
                    {
                        for (int i = 0; i < titles.Length; i++)
                        {
                            this.ErrorList.Columns[i].Text = titles[i];
                        }
                    }
                }

            }

            if (UIControl.Name.ToString().ToUpper() == "CONDITIONLIST")
            {
                ListView bar = UIControl as ListView;

                LanguageItem item = LanguageDB.UIDBTags[this.UIName + "." + bar.Name] as LanguageItem;
                if ((item != null) && (item.Language[LanguageString] != null))
                {
                    string[] titles = item.Language[LanguageString].ToString().Split(new string[] { "||" }, StringSplitOptions.None);

                    if (titles.Length >= 3)
                    {
                        for (int i = 0; i < titles.Length; i++)
                        {
                            this.ConditionList.Columns[i].Text = titles[i];
                        }
                    }
                }

            }


        }


        public event EventHandler SetUserPriviligeEvent = null;
        private void SetUserPrivilige()
        {
            User current = UserDB.CurrentLoginUser;
            this.Text ="RSU Assembly Line"+ current.UserName;
            this.ribbonControl1.TitleText = "<b>RSU Assembly Line (User:" + current.UserName+" login at " + DateTime.Now.ToLocalTime()+")</b>";
            //this.ribbonControl1.Refresh();
            switch (current.AuthorizationSet)
            {
                case 0:
                    this.ribbonManagement.Enabled = true;
                    this.ribbonProduction.Enabled = true;
                    break;
                case 1:
                    this.ribbonManagement.Enabled = false;
                    this.ribbonProduction.Enabled = true;
                    break;
                case 2:
                default:
                    this.ribbonProduction.Enabled = false;
                    this.ribbonManagement.Enabled = false;
                    this.buttonItem39.Visible = false;
                    break;
            }
            SetUserPriviligeEvent(current, null);
            Language_InitializeControl(this);
        }
        //private IUnityContainer container;
        public override void ActiveModule(string UIName)
        {
            AWinFormModule activeModule = ServiceLocator.Current.GetInstance<AWinFormModule>(UIName);
            activeModule.ActivateUI();
            if (this.MainPanel.Controls.Count > 0)
            {
                this.MainPanel.Controls.RemoveAt(0);
            }
            this.MainPanel.Controls.Add(activeModule);
            activeModule.Dock = DockStyle.Fill;
        }

        private void buttonItem1_Click(object sender, EventArgs e)
        {
            this.ActiveModule("MainUI");
        }

        protected override void BackGroud_EventHandler(object sender, StationEventArgs e)
        {
            if (e.From == "MANAGER")
            {
                switch (e.Command)
                {
                    case "ERROR_TAKE":
                        ErrorList.Items.Clear();
                        Dictionary<string, MachineInformationItem> errors = e.Value as Dictionary<string, MachineInformationItem>;
                        foreach (MachineInformationItem item in errors.Values)
                        {
                            AMStudio.Windows.Forms.TreeListItem treeItem = new AMStudio.Windows.Forms.TreeListItem(item.Code);
                            //treeItem.SubItems.Add(item.Code);
                            treeItem.SubItems.Add(item.Station);
                            treeItem.SubItems.Add(item.Message);
                            treeItem.SubItems.Add(item.Address);
                            ErrorList.Items.Add(treeItem);
                        }
                        //if (ErrorList.Items.Count >= 1)
                        //{
                        //    string code = string.Empty;
                        //    if (ErrorList.CheckedItems.Count == 0)
                        //    {
                        //        ErrorList.Items[0].Checked = true;
                        //        code = ErrorList.Items[0].Text.Trim();

                        //    }
                        //    else
                        //    {
                        //        code = ErrorList.CheckedItems[0].SubItems[0].Text.Trim();
                        //    }


                        //    SendMessage("ACTIVE_ERROR", code);
                        //}

                        ErrorList.Invalidate();
                        break;
                    case "CONDITION_TAKE":
                        ConditionList.Items.Clear();
                        Dictionary<string, MachineInformationItem> conditions = e.Value as Dictionary<string, MachineInformationItem>;
                        foreach (MachineInformationItem item in conditions.Values)
                        {
                            AMStudio.Windows.Forms.TreeListItem treeItem = new AMStudio.Windows.Forms.TreeListItem(item.Code);
                            //treeItem.SubItems.Add(item.Code);
                            treeItem.SubItems.Add(item.Station);
                            treeItem.SubItems.Add(item.Message);
                            treeItem.SubItems.Add(item.Address);
                            ConditionList.Items.Add(treeItem);
                        }
                        ConditionList.Invalidate();
                        break;
                    case "EMPTY_LINE":
                        {
                            bool bV = bool.Parse(e.Value.ToString());

                            this.buttonItem14.Checked = bV;
                            this.buttonItem19.Checked = bV;
                            this.buttonItem21.Checked = bV;
                            this.buttonItem35.Checked = bV;
                            this.buttonItem37.Checked = bV;
                        }
                        break;
                    case "TRIAL_RUN":
                        {
                            bool bV = bool.Parse(e.Value.ToString());

                            this.buttonItem39.Checked = bV;
                            this.buttonItem40.Checked = bV;
                            this.buttonItem41.Checked = bV;
                            this.buttonItem42.Checked = bV;
                            this.buttonItem43.Checked = bV;
                        }
                        break;
                }
            }
        }

        

        protected override void UIDB_RfreshTag(Common.UserInterfaceItem item)
        {
            if (item.RelatedControl is SimpleEllipse)
            {
                if ((bool)item.value)
                {
                    item.RelatedControl.ForeColor = System.Drawing.Color.Green;
                }
                else
                {
                    item.RelatedControl.ForeColor = System.Drawing.Color.DarkGray;
                }
            }
            else if (item.RelatedControl is DevComponents.DotNetBar.RibbonBar)
            {
                DevComponents.DotNetBar.RibbonBar button = item.RelatedControl as DevComponents.DotNetBar.RibbonBar;
                int modeState = (int)item.value;
                this.buttonAuto.Checked = false;
                this.buttonCycleStop.Checked = false;
                this.buttonManual.Checked = false;
                this.buttonReset.Checked = false;
                if (modeState == 0)
                {
                    this.buttonAuto.Checked = true;
                }
                else if (modeState == 2)
                {
                    this.buttonManual.Checked = true;
                }
                else if (modeState == 4)
                {
                    this.buttonReset.Checked = true;
                }
                else if (modeState == 8)
                {
                    this.buttonAuto.Checked = true;
                }
                else if (modeState == 16)
                {
                    this.buttonCycleStop.Checked = true;
                }
            }
            else if (item.RelatedControl is DevComponents.DotNetBar.ButtonX)
            {
                DevComponents.DotNetBar.ButtonX button = item.RelatedControl as DevComponents.DotNetBar.ButtonX;

                if (button.Name == "buttonItem17")
                {
                    nNestConfig = (int)item.value;
                }

            }

            //if (item.RelatedControl.Name.ToString().ToUpper()=="SIMPLEELLIPSEAUTO")
            //{
            //    bAuto = (bool)item.value;
            //}
        }
        private bool bAuto = false;


        private int nNestConfig = 0;

        protected override void UIDB_ConnectTagAction(Common.UserInterfaceItem item)
        {
            item.RelatedControl.Click += (sender, e) =>
            {
                DevComponents.DotNetBar.ButtonX button = item.RelatedControl as DevComponents.DotNetBar.ButtonX;
                //if (button.Checked)
                //{
                SendMessage("UIITEM_ACTION", item);
                //}
            };
        }

        private void buttonReset_Click(object sender, EventArgs e)
        {
            SendMessage("MODE_REQUEST", 1);
        }

        private void buttonAuto_Click(object sender, EventArgs e)
        {
            SendMessage("MODE_REQUEST", 2);
        }

        private void buttonManual_Click(object sender, EventArgs e)
        {
            SendMessage("MODE_REQUEST", 0);
        }

        private void buttonCycleStop_Click(object sender, EventArgs e)
        {
            SendMessage("MODE_REQUEST", 3);
        }

        private void buttonItem30_Click(object sender, EventArgs e)
        {
            IUserInterface login = ServiceLocator.Current.GetInstance<IUserInterface>("LoginForm");
            login.ActivateUI();

            SetUserPrivilige();
        }

        private void buttonItem25_Click(object sender, EventArgs e)
        {
            IUserInterface userManager = ServiceLocator.Current.GetInstance<IUserInterface>("UserAccountsForm");
            userManager.ActivateUI();
        }

        private void buttonItem15_Click(object sender, EventArgs e)
        {
            IUserInterface userManager = ServiceLocator.Current.GetInstance<IUserInterface>("WorkorderForm");
            ((WorkorderForm)userManager).StationAuto = this.buttonAuto.Checked;
            userManager.ActivateUI();
        }

        private void buttonItem16_Click(object sender, EventArgs e)
        {
            IUserInterface userManager = ServiceLocator.Current.GetInstance<IUserInterface>("ArticlesForm");
            userManager.ActivateUI();
        }

        private void buttonItem27_Click(object sender, EventArgs e)
        {
            Process.Start("explorer.exe", @"Log\Production");
        }

        private void buttonItem28_Click(object sender, EventArgs e)
        {
            Process.Start("explorer.exe", @"Log\RunLog");
        }

        private void buttonItem29_Click(object sender, EventArgs e)
        {
            Process.Start("explorer.exe", @"Log\RunLog");
        }

        private void buttonItem14_Click(object sender, EventArgs e)
        {
            SendMessage("EMPTY_LINE", !this.buttonItem14.Checked);
        }

        private void buttonItem12_Click(object sender, EventArgs e)
        {

        }

        private void ribbonControl1_SizeChanged(object sender, EventArgs e)
        {

        }

        private void buttonItem33_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void buttonItem14_CheckedChanged(object sender, EventArgs e)
        {
            if (this.buttonItem14.Checked)
            {
                this.buttonItem14.Image = AMStudio.UserInterface.Properties.Resources.empty;
                this.buttonItem19.Image = AMStudio.UserInterface.Properties.Resources.empty;
                this.buttonItem21.Image = AMStudio.UserInterface.Properties.Resources.empty;
                this.buttonItem35.Image = AMStudio.UserInterface.Properties.Resources.empty;
                this.buttonItem37.Image = AMStudio.UserInterface.Properties.Resources.empty;
            }
            else
            {
                this.buttonItem14.Image = AMStudio.UserInterface.Properties.Resources.empty_full;
                this.buttonItem19.Image = AMStudio.UserInterface.Properties.Resources.empty_full;
                this.buttonItem21.Image = AMStudio.UserInterface.Properties.Resources.empty_full;
                this.buttonItem35.Image = AMStudio.UserInterface.Properties.Resources.empty_full;
                this.buttonItem37.Image = AMStudio.UserInterface.Properties.Resources.empty_full;
            }

            //this.buttonItem14.Checked = bV;
            //this.buttonItem19.Checked = bV;
            //this.buttonItem21.Checked = bV;
            //this.buttonItem35.Checked = bV;
            //this.buttonItem37.Checked = bV;
        }

        private void buttonItem39_Click(object sender, EventArgs e)
        {
            SendMessage("TRIAL_RUN", !this.buttonItem39.Checked);
        }

        private void buttonItem39_CheckedChanged(object sender, EventArgs e)
        {
            if (this.buttonItem39.Checked)
            {
                this.buttonItem39.Image = AMStudio.UserInterface.Properties.Resources.trialrun;
                this.buttonItem40.Image = AMStudio.UserInterface.Properties.Resources.trialrun;
                this.buttonItem41.Image = AMStudio.UserInterface.Properties.Resources.trialrun;
                this.buttonItem42.Image = AMStudio.UserInterface.Properties.Resources.trialrun;
                this.buttonItem43.Image = AMStudio.UserInterface.Properties.Resources.trialrun;
            }
            else
            {
                this.buttonItem39.Image = AMStudio.UserInterface.Properties.Resources.trialrun_stop;
                this.buttonItem40.Image = AMStudio.UserInterface.Properties.Resources.trialrun_stop;
                this.buttonItem41.Image = AMStudio.UserInterface.Properties.Resources.trialrun_stop;
                this.buttonItem42.Image = AMStudio.UserInterface.Properties.Resources.trialrun_stop;
                this.buttonItem43.Image = AMStudio.UserInterface.Properties.Resources.trialrun_stop;
            }
        }
        private void buttonItem17_Click(object sender, EventArgs e)
        {
            //IUserInterface userManager = ServiceLocator.Current.GetInstance<IUserInterface>("NestConfigUI");
            //userManager.ActivateUI();

            NestConfigUI fNest = new NestConfigUI();

            MachineConfig config = MachineConfig.Default;

            fNest.NestCfg = config.UICfg.NestCfg;
            if (fNest.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                SendMessage("NEST_CFG", fNest.NestCfg);
                config.UICfg.NestCfg = fNest.NestCfg;

                config.SaveConfig();
            }
        }

        IUserInterface userManager = null;
        private void buttonItem44_Click(object sender, EventArgs e)
        {
            if (userManager == null)
                userManager = ServiceLocator.Current.GetInstance<IUserInterface>("MaterialForm");
            userManager.ActivateUI();
            //materialForm.Show();
        }

        private void ribbonControl1_Resize(object sender, EventArgs e)
        {
            this.label1.Left = ribbonPanel1.ClientSize.Width - this.label1.Width;
            this.label2.Left = ribbonPanel1.ClientSize.Width - this.label2.Width;
            this.label3.Left = ribbonPanel1.ClientSize.Width - this.label3.Width;
            this.label4.Left = ribbonPanel1.ClientSize.Width - this.label4.Width;
            this.label5.Left = ribbonPanel1.ClientSize.Width - this.label5.Width;
        }
    }
}